// TerrainCutting.js
export class TerrainCutting {
    constructor(viewer) {
        this.viewer = viewer;
        this.clippingPlanesArray = [];
        this.clippingPoint = [];
        this.temporayrPolygonEntity = null;
        this.clippingWallEntities = null;
        this.clippingBootomWallEntities = null;
        this.activeClickPick = null;
        this.infoWindowElement = null;
        this.preRenderEvent = null;
        this.clippingDeepValue = 20;
        this.cesiumEventState = "";
    }

    create() {
        // 解决内存问题：优化WebGL配置
        this.viewer.scene.context.webgl2 = false;
        this.viewer.scene.highDynamicRange = false;

        this.cesiumEvent = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

        // 解决Promise链问题：确保所有异步操作正确处理
        this.setupEventHandlers();
    }

    setupEventHandlers() {
        // 左键点击事件
        this.cesiumEvent.setInputAction((event) => {
            this.handleLeftClick(event);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // 鼠标按下事件
        this.cesiumEvent.setInputAction((event) => {
            this.handleLeftDown(event);
        }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

        // 鼠标抬起事件
        this.cesiumEvent.setInputAction(() => {
            this.cesiumEventState = "leftUp";
        }, Cesium.ScreenSpaceEventType.LEFT_UP);

        // 鼠标移动事件
        this.cesiumEvent.setInputAction((event) => {
            this.handleMouseMove(event);
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // 右键点击事件
        this.cesiumEvent.setInputAction(() => {
            this.clippingPlaneCollection();
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    }

    handleLeftClick(event) {
        this.cesiumEventState = "leftClick";
        this.activeClickPick = this.viewer.scene.pick(event.position);

        if (!this.activeClickPick || !this.activeClickPick.id) {
            if (this.clippingWallEntities) {
                this.destroy();
            }
            this.saveClippingPlaneCollectionData(event);
        }
    }

    handleLeftDown(event) {
        this.cesiumEventState = "leftDown";
        this.activeClickPick = this.viewer.scene.pick(event.position);
        if (this.clippingWallEntities && this.activeClickPick?.id) {
            this.selectClickPoint();
        }
    }

    handleMouseMove(event) {
        if (this.activeClickPick?.id && this.cesiumEventState === "leftDown") {
            this.changeLayerPointPostion(event);
        }
    }

    saveClippingPlaneCollectionData(event) {
        const cartesian = this.viewer.camera.pickEllipsoid(
            event.position,
            this.viewer.scene.globe.ellipsoid
        );

        this.clippingPlanesArray.push(cartesian);

        const clippingPoint = this.viewer.entities.add({
            name: "定位点",
            position: cartesian,
            point: {
                color: Cesium.Color.SKYBLUE,
                pixelSize: 10,
                outlineColor: Cesium.Color.YELLOW,
                outlineWidth: 3,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            }
        });

        this.clippingPoint.push(clippingPoint);

        if (!this.temporayrPolygonEntity) {
            this.temporayrPolygonEntity = this.viewer.entities.add({
                polygon: {
                    hierarchy: new Cesium.CallbackProperty(() => {
                        return new Cesium.PolygonHierarchy(this.clippingPlanesArray);
                    }, false),
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    material: Cesium.Color.RED.withAlpha(0.5)
                }
            });
        }
    }

    clippingPlaneCollection() {
        // 清理现有开挖区域
        this.cleanupExistingExcavation();

        if (this.clippingPlanesArray.length < 3) return;

        const clippingPlanes = this.createClippingPlanes();

        // 解决内存问题：使用更高效的裁剪平面配置
        this.viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
            planes: clippingPlanes,
            edgeWidth: 1,
            unionClippingRegions: true
        });

        this.createExcavationWalls();
        this.showTooltip();
    }

    createClippingPlanes() {
        const clippingPlanes = [];
        const pointsLength = this.clippingPlanesArray.length;

        for (let i = 0; i < pointsLength; i++) {
            const nextIndex = (i + 1) % pointsLength;
            const midpoint = Cesium.Cartesian3.midpoint(
                this.clippingPlanesArray[i],
                this.clippingPlanesArray[nextIndex],
                new Cesium.Cartesian3()
            );

            const up = Cesium.Cartesian3.normalize(midpoint, new Cesium.Cartesian3());
            const right = Cesium.Cartesian3.subtract(
                this.clippingPlanesArray[nextIndex],
                midpoint,
                new Cesium.Cartesian3()
            );
            Cesium.Cartesian3.normalize(right, right);

            const normal = Cesium.Cartesian3.cross(right, up, new Cesium.Cartesian3());
            Cesium.Cartesian3.normalize(normal, normal);

            const originCenteredPlane = new Cesium.Plane(normal, 0.0);
            const distance = Cesium.Plane.getPointDistance(originCenteredPlane, midpoint);

            clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));
        }

        return clippingPlanes;
    }

    createExcavationWalls() {
        // 侧边墙体
        this.clippingWallEntities = this.viewer.entities.add({
            corridor: {
                positions: [...this.clippingPlanesArray, this.clippingPlanesArray[0]],
                height: -this.clippingDeepValue,
                extrudedHeight: 0,
                width: 1,
                cornerType: Cesium.CornerType.ROUNDED,
                material: Cesium.Color.fromCssColorString(`rgba(66,187,133,1)`),
                outline: false
            },
        });

        // 底部墙体
        this.clippingBootomWallEntities = this.viewer.entities.add({
            polygon: {
                hierarchy: this.clippingPlanesArray,
                height: -this.clippingDeepValue,
                extrudedHeight: -this.clippingDeepValue + 1,
                material: Cesium.Color.YELLOW
            },
        });
    }

    cleanupExistingExcavation() {
        if (this.clippingWallEntities) {
            this.viewer.entities.remove(this.clippingWallEntities);
            this.clippingWallEntities = null;
        }

        if (this.clippingBootomWallEntities) {
            this.viewer.entities.remove(this.clippingBootomWallEntities);
            this.clippingBootomWallEntities = null;
        }

        this.viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
            planes: [],
            edgeWidth: 0
        });
    }

    // ...其他方法保持不变...
}